package com.bee.auth.client.interceptor;

import com.bee.auth.client.AuthHolder;
import com.bee.auth.client.util.HttpSecurityUtil;
import com.google.common.collect.Maps;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author Damin.yang
 * @date 2019/08/25 20:13
 */
@RefreshScope
@Configuration
public class FeignOauthRequestInterceptor implements RequestInterceptor {

    private static final String CLIENT_ID = "clientId";

    @Value("${spring.application.name}")
    private String clientId;
    @Value("${auth.jwt.signingKey}")
    private String secretKey;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // TODO Auto-generated method stub
        if (StringUtils.isEmpty(AuthHolder.getToken())) {
            // 加上服务间调用简单校验
            Map<String, Object> map = Maps.newHashMap();
            map.put(CLIENT_ID, clientId);
            requestTemplate.header(HttpSecurityUtil.CLIENT_TOKEN_NAME, HttpSecurityUtil.createJwtToken(map, secretKey));
        } else {
            requestTemplate.header(HttpSecurityUtil.TOKEN_NAME, AuthHolder.getToken());
        }
    }
}
